﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using Actya.Core.Infrastructure;

namespace Actya.Web.Mvc
{
	public class CmsHelper
	{
		public ViewContext ViewContext { get; private set; }
		public ICmsContext CmsContext { get; private set; }
		
		public CmsHelper(ViewContext viewContext,  ICmsContext cmsContext)
		{
			ViewContext = viewContext;
			CmsContext = cmsContext;
		}

		public MvcHtmlString PageTitle()
		{
			var title = this.CmsContext.Page != null ? this.CmsContext.Page.Title : String.Empty;
			return MvcHtmlString.Create(title);
		}
	}

	public class CmsHelper<TModel> : CmsHelper
	{
		public ViewDataDictionary<TModel> ViewData { get; private set; }
		public HtmlHelper<TModel> HtmlHelper { get; private set; }

		public CmsHelper(ViewContext viewContext, IViewDataContainer container, ICmsContext cmsContext, HtmlHelper<TModel> htmlHelper) 
			: base (viewContext, cmsContext)
		{
			ViewData = new ViewDataDictionary<TModel>(container.ViewData);
			HtmlHelper = htmlHelper;
		}

		public HtmlString ContentRegion(string regionName)
		{
			return ContentRegion(regionName, null);
		}

		public HtmlString ContentRegion(string regionName, string content)
		{
			var regionContent = String.Empty;

			// Render the given content first
			if (!String.IsNullOrEmpty(content))
			{
				regionContent += content;
			}

			// Render widgets
			var pageLayout = this.CmsContext.GetCurrentPageLayout();
			if (pageLayout != null)
			{
				if (pageLayout.Widgets.ContainsKey(regionName))
				{
					var widgetIds = pageLayout.Widgets[regionName];
					foreach (var widgetId in widgetIds)
					{
						var widgetContent = HtmlHelper.Action("Display", "Widget", new {widgetId});
						regionContent += widgetContent;
					}
				}
			}
			return MvcHtmlString.Create(regionContent);
		}
	}
}